//
//  SlideTabContainerController.m
//  LotteryClient
//
//  Created by SunYu-Mac on 14-2-21.
//  Copyright (c) 2014年 SunYu. All rights reserved.
//

#import "SlideTabContainerController.h"
#import "SlideTabViewController.h"
#import "SlideTabInfoMedol.h"

static const CGFloat kHeightOfTopScrollView = 33.0;
static const CGFloat kWidthOfButtonMargin = 10;
static const CGFloat kFontSizeOfTabButton = 15.0f;
static const NSUInteger kTagOfRightSideButton = 999;


@interface SlideTabContainerController ()
@property (nonatomic, strong)NSMutableDictionary *dictionary;

@end

@implementation SlideTabContainerController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabItemNormalColor = [[self class] colorFromHexRGB:@"8d8d8d"];
        self.tabItemSelectedColor = [[self class]colorFromHexRGB:@"ae2526"];
        self.shadowImage = [[UIImage imageNamed:@"slide_tab_selected_Shadow.png"]
                stretchableImageWithLeftCapWidth:59.0f topCapHeight:0.0f];

        self.dictionary = [NSMutableDictionary dictionary];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.frame = CGRectMake(0,
								 0, 
								 self.view.frame.size.width, 
								 self.view.frame.size.height);
    self.switchAnimate = NO;

    [self initSubViews];

    [self buildUI];
    [self layoutSubviews];

    [self setSelectIndex:_selectIndex];
}


- (void)initSubViews
{
    CGRect frame = CGRectMake(0,
							  0,
							  self.view.width, 
							  kHeightOfTopScrollView);
	
    if(self.hasNavigationBar)
    {
        frame.origin.y += self.navigationBarHeight;
    }
	
    //创建顶部可滑动的tab
    _topScrollView = [[UIScrollView alloc] initWithFrame:frame];
    _topScrollView.delegate = self;
    _topScrollView.pagingEnabled = NO;
    _topScrollView.showsHorizontalScrollIndicator = NO;
    _topScrollView.showsVerticalScrollIndicator = NO;
    _topScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    _topScrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"slide_tab_scroll_background.png"]];

    [self.view addSubview:_topScrollView];
    _userSelectedChannelID = 100;

    //创建主滚动视图
    _rootScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 
																	 kHeightOfTopScrollView + frame.origin.y + 2, 
																	 self.view.bounds.size.width,
																	 self.view.bounds.size.height - kHeightOfTopScrollView)];
    _rootScrollView.delegate = self;
    _rootScrollView.pagingEnabled = YES;
    _rootScrollView.userInteractionEnabled = YES;
    _rootScrollView.bounces = NO;
    _rootScrollView.showsHorizontalScrollIndicator = YES;
    _rootScrollView.showsVerticalScrollIndicator = NO;
    _rootScrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    _userContentOffsetX = 0;

	[_rootScrollView.panGestureRecognizer addTarget:self action:@selector(scrollHandlePan:)];
    [self.view addSubview:_rootScrollView];


    _isBuildUI = NO;

}


- (UIViewController *)createViewControllerWith:(id<SlideTabInfoMedol>)slideTabInfo
{

	UIViewController *viewController = (UIViewController *)[self.dictionary objectForKey:slideTabInfo.tabTitle];
    if (viewController)
    {
        return viewController;
    }
	if ([slideTabInfo viewController] &&[[slideTabInfo viewController] isSubclassOfClass:[SlideTabViewController class]])
	{
		Class cla = [slideTabInfo viewController];
		viewController = [[cla alloc] initWithSlideInfo:slideTabInfo];
    }
    else if ([slideTabInfo viewController] &&[[slideTabInfo viewController] isSubclassOfClass:[UIViewController class]])
    {
        viewController = [[[slideTabInfo viewController] alloc] init];
    }
    else
    {
        return nil;
    }

	NSInteger index = [self.tabInfoArray indexOfObject: slideTabInfo];
    if (viewController)
    {
        [self.dictionary setObject:viewController
                            forKey:slideTabInfo.tabTitle];
		
		viewController.view.frame = CGRectMake(0 + _rootScrollView.bounds.size.width * index,
											   0,
											   _rootScrollView.bounds.size.width,
											   _rootScrollView.bounds.size.height);

    }
	
//	UIColor *color ;
//	if (index % 2 == 0)
//	{
//		color = [UIColor redColor];
//	}
//	else
//	{
//		color = [UIColor greenColor];
//	}
//	
//	viewController.view.backgroundColor = color;
	if ([viewController isKindOfClass:[BaseViewController class]])
	{
		[(BaseViewController *)viewController setCustomNavigationController:self.navigationController];
	}
    return viewController;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];


    id<SlideTabInfoMedol> tabInfo = [self.tabInfoArray objectAtIndex:self.selectIndex];
    UIViewController *controller = [self createViewControllerWith:tabInfo];

    [_rootScrollView addSubview:controller.view];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
	
	
}

- (void)dealloc
{
    if ([_viewControllers isKindOfClass:[NSMutableArray class]])
    {
        [_viewControllers removeAllObjects];
    }
}

- (NSInteger)selectIndex
{
    return _userSelectedChannelID - 100;
}
- (void)setSelectIndex:(NSInteger)selectIndex
{
    _selectIndex = selectIndex;

    UIButton *button = (UIButton *)[_topScrollView viewWithTag:selectIndex + 100];

    if (button)
    {
        [self selectNameButton:button];
    }
	
	id<SlideTabInfoMedol> tabInfo = [self.tabInfoArray objectAtIndex:_selectIndex];
	UIViewController *controller = [self createViewControllerWith:tabInfo];
	
	[self.view addSubview:controller.view];

}

#pragma mark getter/setter

- (void)setRigthSideButton:(UIButton *)rigthSideButton
{
    UIButton *button = (UIButton *)[self.view viewWithTag:kTagOfRightSideButton];
    [button removeFromSuperview];
    rigthSideButton.tag = kTagOfRightSideButton;
    _rigthSideButton = rigthSideButton;
    [self.view addSubview:_rigthSideButton];

}

#pragma mark - 创建控件

/*!
 * @method 创建子视图UI
 * @abstract
 * @discussion
 * @param
 * @result
 */
- (void)buildUI
{
    [self createNameButtons];

    _isBuildUI = YES;

    //创建完子视图UI才需要调整布局
    [self.view setNeedsLayout];
}


//当横竖屏切换时可通过此方法调整布局
- (void)layoutSubviews
{
    //创建完子视图UI才需要调整布局
    if (_isBuildUI)
    {
        //如果有设置右侧视图，缩小顶部滚动视图的宽度以适应按钮
        if (self.rigthSideButton.bounds.size.width > 0)
        {
            _rigthSideButton.frame = CGRectMake(self.view.bounds.size.width - self.rigthSideButton.bounds.size.width, 0,
                    _rigthSideButton.bounds.size.width, _topScrollView.bounds.size.height);

            _topScrollView.frame = CGRectMake(0, 0,
                    self.view.bounds.size.width - self.rigthSideButton.bounds.size.width, kHeightOfTopScrollView);
        }

        //更新主视图的总宽度
		_rootScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * [_tabInfoArray count], 0);

        //滚动到选中的视图
        [_rootScrollView setContentOffset:CGPointMake((_userSelectedChannelID - 100)*self.view.bounds.size.width, 0) animated:NO];

        //调整顶部滚动视图选中按钮位置
        UIButton *button = (UIButton *)[_topScrollView viewWithTag:_userSelectedChannelID];
        [self adjustScrollViewContentX:button];
    }
}


/*!
 * @method 初始化顶部tab的各个按钮
 * @abstract
 * @discussion
 * @param
 * @result
 */
- (void)createNameButtons
{

    _shadowImageView = [[UIImageView alloc] init];
    [_shadowImageView setImage:_shadowImage];
    [_topScrollView addSubview:_shadowImageView];

    //顶部tabbar的总长度
    CGFloat topScrollViewContentWidth = 0;
    //每个tab偏移量
    CGFloat xOffset = 0;

    NSInteger count = [_tabInfoArray count];
    if (count == 0)return;
    for (NSUInteger i = 0; i < count; i++)
    {
		id<SlideTabInfoMedol> tabInfo = [_tabInfoArray objectAtIndex:i];
        CGSize textSize = [[tabInfo tabTitle] sizeWithFont:[UIFont systemFontOfSize:kFontSizeOfTabButton]
                               constrainedToSize:CGSizeMake(_topScrollView.bounds.size.width, kHeightOfTopScrollView)
                                   lineBreakMode:NSLineBreakByTruncatingTail];
        //累计每个tab文字的长度
        topScrollViewContentWidth += 2 * kWidthOfButtonMargin + textSize.width;

    }

    int increase = 0;
    if (topScrollViewContentWidth < _topScrollView.frame.size.width)
    {
        DLog(@"%f",_topScrollView.frame.size.width);
        increase = _topScrollView.frame.size.width - topScrollViewContentWidth;
        increase = increase/count;
    }

    topScrollViewContentWidth = kWidthOfButtonMargin;
    for (int i = 0; i < count; i++)
    {
		id<SlideTabInfoMedol> tabInfo = [_tabInfoArray objectAtIndex:i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        CGSize textSize = [[tabInfo tabTitle] sizeWithFont:[UIFont systemFontOfSize:kFontSizeOfTabButton]
                               constrainedToSize:CGSizeMake(_topScrollView.bounds.size.width, kHeightOfTopScrollView)
                                   lineBreakMode:NSLineBreakByTruncatingTail];
		
        textSize.width = textSize.width + increase + 2*kWidthOfButtonMargin;
        //累计每个tab文字的长度
        topScrollViewContentWidth += textSize.width;
        //设置按钮尺寸
        [button setFrame:CGRectMake(xOffset,0,
                textSize.width, kHeightOfTopScrollView)];
        //增加分割线
        if (i != (count - 1))
        {

            UIImageView * cutView = nil;

            cutView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"slide_tab_interval_line.png"]];

            cutView.frame = CGRectMake(button.right, 0, 1, kHeightOfTopScrollView);
			
            [_topScrollView addSubview:cutView];
			
        }
        //计算下一个tab的x偏移量
        xOffset += textSize.width;

        [button setTag:i+100];
        if (i == 0)
        {
            _shadowImageView.frame = CGRectMake(0+kWidthOfButtonMargin,
												0, 
												textSize.width - 2*kWidthOfButtonMargin, 
												kHeightOfTopScrollView);
            button.selected = YES;
        }
        [button setTitle:[tabInfo tabTitle]  forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:kFontSizeOfTabButton];
        [button setTitleColor:self.tabItemNormalColor forState:UIControlStateNormal];
        [button setTitleColor:self.tabItemSelectedColor forState:UIControlStateSelected];
        [button setBackgroundImage:self.tabItemNormalBackgroundImage forState:UIControlStateNormal];
        [button setBackgroundImage:self.tabItemSelectedBackgroundImage forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectNameButton:) forControlEvents:UIControlEventTouchUpInside];
        [_topScrollView addSubview:button];


    }
	
    //设置顶部滚动视图的内容总尺寸
    _topScrollView.contentSize = CGSizeMake(topScrollViewContentWidth, kHeightOfTopScrollView);
}


#pragma mark - 顶部滚动视图逻辑方法

/*!
 * @method 选中tab时间
 * @abstract
 * @discussion
 * @param 按钮
 * @result
 */
- (void)selectNameButton:(UIButton *)sender
{
    //如果点击的tab文字显示不全，调整滚动视图x坐标使用使tab文字显示全
    [self adjustScrollViewContentX:sender];

    //如果更换按钮
    if (sender.tag != _userSelectedChannelID) {
        //取之前的按钮
        UIButton *lastButton = (UIButton *)[_topScrollView viewWithTag:_userSelectedChannelID];
        lastButton.selected = NO;
        //赋值按钮ID
        _userSelectedChannelID = sender.tag;
    }

    //按钮选中状态
    if (!sender.selected)
	{
        sender.selected = YES;
//		[[self.viewControllers objectAtIndex:_userSelectedChannelID - 100] viewWillAppear:YES];

        [UIView animateWithDuration:0.0 animations:^{

            [_shadowImageView setFrame:CGRectMake(sender.frame.origin.x + kWidthOfButtonMargin, 0, sender.frame.size.width - 2*kWidthOfButtonMargin,kHeightOfTopScrollView)];

        } completion:^(BOOL finished) {
            if (finished) {
                //设置新页出现
                if (!_isRootScroll) {
                    [_rootScrollView setContentOffset:CGPointMake((sender.tag - 100)*self.view.bounds.size.width, 0) animated:self.switchAnimate];
                    self.switchAnimate = YES;
                }
                _isRootScroll = NO;

                if (self.slideSwitchViewDelegate && [self.slideSwitchViewDelegate respondsToSelector:@selector(slideSwitchView:didselectTab:)])
                {
                    [self.slideSwitchViewDelegate slideSwitchView:self didselectTab:_userSelectedChannelID - 100];
                }
            }
        }];

    }
            //重复点击选中按钮
    else {

    }
	
	
	NSInteger index = sender.tag - 100;
	
	UIViewController *controller = [self createViewControllerWith:[self.tabInfoArray objectAtIndex:index]];
 
	[_rootScrollView addSubview:controller.view];
//	self.selectIndex = index;
}

/*!
 * @method 调整顶部滚动视图x位置
 * @abstract
 * @discussion
 * @param
 * @result
 */
- (void)adjustScrollViewContentX:(UIButton *)sender
{
    //如果 当前显示的最后一个tab文字超出右边界
    if (sender.frame.origin.x - _topScrollView.contentOffset.x > self.view.bounds.size.width - (kWidthOfButtonMargin+sender.bounds.size.width)) {
        //向左滚动视图，显示完整tab文字
        [_topScrollView setContentOffset:CGPointMake(sender.frame.origin.x - (_topScrollView.bounds.size.width- (kWidthOfButtonMargin+sender.bounds.size.width)), 0)  animated:YES];
    }

    //如果 （tab的文字坐标 - 当前滚动视图左边界所在整个视图的x坐标） < 按钮的隔间 ，代表tab文字已超出边界
    if (sender.frame.origin.x - _topScrollView.contentOffset.x < kWidthOfButtonMargin) {
        //向右滚动视图（tab文字的x坐标 - 按钮间隔 = 新的滚动视图左边界在整个视图的x坐标），使文字显示完整
        [_topScrollView setContentOffset:CGPointMake(sender.frame.origin.x - kWidthOfButtonMargin, 0)  animated:YES];
    }
}

- (void)loadPages
{
	CGFloat pageWidth = _rootScrollView.frame.size.width;
	NSInteger pageIndex = floor((_rootScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	self.selectIndex = pageIndex;
}


#pragma mark 主视图逻辑方法

//滚动视图开始时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == _rootScrollView) 
	{
        _userContentOffsetX = scrollView.contentOffset.x;
    }
}
//滚动视图结束
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _rootScrollView)
    {
        //判断用户是否左滚动还是右滚动
        if (_userContentOffsetX < scrollView.contentOffset.x)
        {
            _isLeftScroll = YES;
        }
        else
        {
            _isLeftScroll = NO;
        }
//		[self loadPages];

    }
}

//滚动视图释放滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _rootScrollView) 
	{
        _isRootScroll = YES;
        //调整顶部滑条按钮状态
        int tag = (int)scrollView.contentOffset.x/self.view.bounds.size.width +100;
        UIButton *button = (UIButton *)[_topScrollView viewWithTag:tag];
        [self selectNameButton:button];
    }
}

//传递滑动事件给下一层
-(void)scrollHandlePan:(UIPanGestureRecognizer*) panParam
{
    //当滑道左边界时，传递滑动事件给代理
    if(_rootScrollView.contentOffset.x <= 0)
	{
        if (self.slideSwitchViewDelegate
                && [self.slideSwitchViewDelegate respondsToSelector:@selector(slideSwitchView:panLeftEdge:)])
		{
            [self.slideSwitchViewDelegate slideSwitchView:self panLeftEdge:panParam];
        }
    } else if(_rootScrollView.contentOffset.x >= _rootScrollView.contentSize.width - _rootScrollView.bounds.size.width) {
        if (self.slideSwitchViewDelegate
                && [self.slideSwitchViewDelegate respondsToSelector:@selector(slideSwitchView:panRightEdge:)]) {
            [self.slideSwitchViewDelegate slideSwitchView:self panRightEdge:panParam];
        }
    }
}

#pragma mark - 工具方法

/*!
 * @method 通过16进制计算颜色
 * @abstract
 * @discussion
 * @param 16机制
 * @result 颜色对象
 */
+ (UIColor *)colorFromHexRGB:(NSString *)inColorString
{
    UIColor *result = nil;
    unsigned int colorCode = 0;
    unsigned char redByte, greenByte, blueByte;

    if (nil != inColorString)
    {
        NSScanner *scanner = [NSScanner scannerWithString:inColorString];
        (void) [scanner scanHexInt:&colorCode]; // ignore error
    }
    redByte = (unsigned char) (colorCode >> 16);
    greenByte = (unsigned char) (colorCode >> 8);
    blueByte = (unsigned char) (colorCode); // masks off high bits
    result = [UIColor
            colorWithRed: (float)redByte / 0xff
                   green: (float)greenByte/ 0xff
                    blue: (float)blueByte / 0xff
                   alpha:1.0];
    return result;
}


@end
